<?php
/**
 * @package		Joomla.Site
 * @subpackage	com_search
 * @copyright	Copyright (C) 2005 - 2013 Open Source Matters, Inc. All rights reserved.
 * @license		GNU General Public License version 2 or later; see LICENSE.txt
 */

defined('_JEXEC') or die;

$helper = JPATH_COMPONENT.'/helpers/glycophile.php';
require_once($helper);

/**
 *
 * @package		Joomla.Site
 * @subpackage	com_glycophile
 * @since 1.5
 */
class GlycophileModelSearch extends JModelLegacy
{
	/**
	 * data array
	 *
	 * @var array
	 */
	var $_data = null;

	/**
	 * total
	 *
	 * @var integer
	 */
	var $_total = null;

	/**
	 * Pagination object
	 *
	 * @var object
	 */
	var $_pagination = null;
	
	/**
	 * Helper
	 *
	 * @var object
	 */
	var $_helper = null;
	
	var $_theme = null;

	/**
	 * Constructor
	 *
	 * @since 1.5
	 */
	function __construct()
	{
		parent::__construct();

		//Get configuration
		$app	= JFactory::getApplication();
		$config = JFactory::getConfig();
		
		$this->_helper = new GlycophileHelper();

		// Get the pagination request variables
		$this->setState('limit', $app->getUserStateFromRequest('com_search.limit', 'limit', $config->get('list_limit'), 'uint'));
		$this->setState('limitstart', JRequest::getUInt('limitstart', 0));
	
		$this->countAllRows();
		$this->getList();
		$this->_theme = $this->_helper->getThemesById(JRequest::getVar('theme', 0));
	}

	/**
	 * Method to get Series list
	 * Si theme sélectionné  (exemple Sujet divers id = 16 )
	 *
	 * @access public
	 * @return array
	 */
	function getData()
	{
		return $this->_data;
	}
	
	function getTheme()
	{
		return $this->_theme;
	}
	
	function getTotal()
	{
		return $this->_total;
	}
	
	function getPagination()
	{
		return $this->_pagination;
	}
	
	function getQuery($searchMode = 1, $keyword = '', $orderBy = null, $order = 'ASC'){

		
		$filter_pays = JRequest::getVar('filter_pays', '');
		
		if($searchMode == 1){ // id_pays
			$query = "SELECT s.*, s.id_theme, COUNT(DISTINCT(ss.id)) AS variante, s.datemodif , th.code, th.theme, p.identPays as pays_id, p.pays ";
			$query .= " FROM #__glycophile_serie s, #__glycophile_sousserie ss,  #__glycophile_theme th, #__glycophile_pays p ";
		//	$query .= " INNER JOIN #__glycophile_pays p ON p.id = th.`identpays` ";
			$query .= " WHERE ss.state = 1 AND s.state = 1"; // AND t.state = 1";
			$query .= " AND p.identPays = s.id_pays";
			$query .= " AND ss.id_serie = s.id"; 
		//	$query .= " AND s.id_tome = t.id";
			$query .= " AND s.id_theme = th.id";
      $query .= " AND s.calcul_serie > 0 AND ss.calcul_serie > 0";
			$query .= $filter_pays != '' ? " AND p.id = ".$filter_pays : '';
			//$query .= $keyword != '' ? " AND s.serie LIKE '%".$keyword."%'" : '';
      $query .= $keyword != '' ? " AND MATCH ( s.serie ) AGAINST ( '".$keyword."' )" : '';
			$query .= " GROUP BY s.id";
			$query .= " ORDER BY p.id, s.page DESC";
 
		}elseif($searchMode == 2){
			$query = "SELECT s.*, p.id as pays_id, p.pays FROM `#__glycophile_sucre` s";
			$query .= " INNER JOIN #__glycophile_pays p ON p.identPays = s.`id_pays` ";
	//		$query .= $keyword != '' ? " WHERE designation LIKE '%".$keyword."%'" : '';
      $query .= $keyword != '' ? " WHERE MATCH ( designation ) AGAINST ( '".$keyword."' )" : '';
			$query .= $filter_pays != '' ? " AND p.id = ".$filter_pays : '';
			$query .= " ORDER BY p.id, s.rang ASC";
		}

		//echo '<br />- '.str_replace('#__','glyco_',$query); //
		return $query ;
	}
	
	function countAllRows(){
		$db = $this->getDbo();
		$searchMode = JRequest::getVar('searchMode', 1);
		$keyword = JRequest::getVar('keyword', '');
		$query = $this->getQuery($searchMode, $keyword);
		$db->setQuery($query);
		$items = $db->query($searchMode, $keyword);
		$this->_total = $db->getNumRows();
	}
	
	function getList(){
		$db = $this->getDbo();
		global $mainframe;
		//Get configuration
		$config = JFactory::getConfig();
		// Get the pagination request variables
		
		$limitstart = JRequest::getUInt('limitstart', 1);
		$limit = $config->getValue('config.list_limit');
		$ligne = ($limitstart - 1) * $limit;
		$searchMode = JRequest::getVar('searchMode', 1);
		$keyword = JRequest::getVar('keyword', '');
		
		if($searchMode == 1){
			//$orderBy = JRequest::getVar('orderBy', "s.page");
			//$order = JRequest::getVar('order', 'DESC');
			$query = $this->getQuery($searchMode, $keyword);
			$query .= " Limit ". $ligne .", ". $limit; 
			
			$db->setQuery($query);
			$series = $db->loadObjectList();
			
			foreach($series as $serie){
				$query = "Select * From #__glycophile_sousserie ss";
				$query .= "	Where id_serie = ".$serie->id;
				$db->setQuery($query);
				$sseries = $db->loadObjectList();
				$serie->sseries = $sseries;
			}
			
			$this->_data = $series;
		}elseif($searchMode == 2){
			//////////////////////
			//$orderBy = JRequest::getVar('orderBy', 'rang');
			//$order = JRequest::getVar('order', 'ASC');
			$query = $this->getQuery($searchMode, $keyword);
			$query .= " Limit ". $ligne .", ". $limit; 

			$db->setQuery($query);
			$sucres = $db->loadObjectList();
			
			$imgs = array();
			
			foreach($sucres as $sucre){

				$q = "SELECT *
				FROM `#__glycophile_inventaire`
				WHERE `id_sucre` =". $sucre->id ;
				$db->setQuery($q);
				$inventaires = $db->loadObjectList();
		  
				foreach($inventaires as $inventaire){
					$imgs = $this->getImgPathSucre($sucre->id_serie , $inventaire->id);
				}

				if(isset($imgs[0]->URL)){
					
					$ima = 'components/com_glycophile/asset/images/'.$imgs[0]->URL ;
					$imageData = $this->_helper->preAffiche_Image3($ima, 0.33, $sucre->designation);
					
					$sucre->imgPath = $imageData['imgPath'] ;
					$sucre->rimgPath = $imageData['rimgPath'] ;
					$sucre->img = $imageData['img'];
					if(isset($imageData['rimg'])) { $sucre->rimg = $imageData['rimg']; }
				}
			}
			
			$this->_data = $sucres;
			//////////////////////
		}

		$Itemid = JRequest::getVar('Itemid', 0);
		$url = 'index.php?option=com_glycophile&view=search&searchMode='.$searchMode.'&keyword='. $keyword .'&Itemid='.$Itemid;
		//$url .= '&orderBy='. $orderBy .'&order='.$order;
		$this->_pagination = $this->_helper->getPaginationBar($this->_total, $limit, $url);
	}
	
	function getImgPathSucre($serieId , $inventaireId){
		
		$db = $this->getDbo();
		$query = "SELECT concat(s.id_pays, '/', t.code,'/', s.id, '/', i.id , '.jpg') URL
		FROM `#__glycophile_pays` p, #__glycophile_theme t, #__glycophile_serie s,
		#__glycophile_sousserie ss, #__glycophile_inventaire i 
		WHERE t.identpays= s.id_pays
		AND p.identpays = s.id_pays AND t.id= s.id_theme
		AND ss.id_serie = s.id 
		AND i.id_sous_serie = ss.id
		AND i.TailleX > 0 AND i.TailleY > 0
		AND s.id=".$serieId. " AND i.id=".$inventaireId;
		
		
		$db->setQuery($query);
		$url = $db->loadObjectList();
		return $url;
	}

}
